var jwt = require('jsonwebtoken');
var sql = require('../mysql.js');

var fn_login = async(ctx, next) => {
    "use strict";

    //传入参数
    var data = ctx.request.query;
    var sqls = `SELECT * from user WHERE userName = '${data.userName}' AND psd = ${data.psd}`;

    //response 结果存放对象
    var res = {};

    //查询结果
    var sqlRes = await sql(sqls);

    if (sqlRes.length <= 0) {
        res.msg = "账户或者密码错误";
        res.status = 1;
    } else {
        res = sqlRes[0];
        res.status = 0;
        res.msg = "登录成功";

        //token 验证
        var isOk = await new Promise((resolve, reject) => {
            jwt.verify(res.token, 'prhhh', function(err, decode) {
                resolve(decode);
            });
        })

        if (!isOk) {
            var token = jwt.sign({
                data: res.userName
            }, 'prhhh', {
                expiresIn: '1h'
            });
            await sql(`UPDATE user SET token = '${token}' WHERE id = ${res.id}`);
            res.token = token;
        }
    }

    //JSON 字符串
    ctx.response.body = JSON.stringify(res);
};

var fn_register = async(ctx, next) => {
    "use strict";

    //获取注册用户名,密码
    var data = ctx.request.query;

    //查询结果
    var res = {};

    //验证是否有重复用户名
    var sqls_1 = `SELECT * from user WHERE userName = '${data.userName}'`;
    var sqls_2 = `INSERT INTO user(userName, psd)
                    VALUES('${data.userName}', ${data.psd})`;

    var res_1 = await sql(sqls_1);

    if (res_1.length <= 0) {
        var sqlRes = await sql(sqls_2);
        res.status = 0;
        res.msg = '注册成功';
    } else {
        res.status = 1;
        res.msg = "改用户名已被注册"
    }

    //JSON 字符串
    ctx.response.body = JSON.stringify(res);
}

var fn_searchUser = async(ctx, next) => {
    var data = ctx.request.query;
    //结果对象
    var res = {};
    console.log('search', data);
    var sqls = `SELECT * FROM user WHERE userName LIKE '%${data.userName}%' AND id<>${data.id}`;
    var sqlRes = await sql(sqls);
    if(sqlRes.length <= 0) {
        res.status = 1;
        res.msg = '没有'
    }else {
        res.status = 0;
        res.data = sqlRes;
    }
    ctx.response.body = res;
}
module.exports = {
    'POST /api/login': fn_login,
    'POST /api/register': fn_register,
    'POST /api/searchUser' : fn_searchUser
};